//
//  TimerAddViewModel.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/11/9.
//

import UIKit
import ETKit
import SVProgressHUD

let kTimerDefaultName = "计时器名称"

enum TimerType: String {
    /// 正计时（指定时间段计时）
    case timeSlotTiming = "正计时"
    /// 计时器（单纯计时）
    case timer = "纯计时"
    /// 倒计时
    case countDown = "倒计时"
    
    var id: Int32 {
        switch self {
        case .timeSlotTiming: return 1
        case .timer: return 2
        case .countDown: return 3
        }
    }
    
    /// 根据ID获取type
    /// - Parameter id: id
    /// - Returns: TimerType
    static func getType(id: Int32) -> TimerType {
        switch id {
        case 1: return .timeSlotTiming
        case 2: return .timer
        case 3: return .countDown
        default: return .timeSlotTiming
        }
    }
}

enum TimeType {
    case start
    case end
}

struct Time: Equatable {
    var hour: Int
    var minute: Int
    
    static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.toSeconds() == rhs.toSeconds()
    }
    
    /// 转换成秒数
    func toSeconds() -> Int {
        return (hour * 60 * 60) + (minute * 60)
    }
    
    init(hour: Int, minute: Int) {
        self.hour = hour
        self.minute = minute
    }
    
    init(seconds: TimeInterval) {
        let formatTime = seconds.et.formatTime("HH:mm")
        let time = formatTime.components(separatedBy: ":")
        self.hour = Int(time.first ?? "0") ?? 0
        self.minute = Int(time.last ?? "0") ?? 0
    }
}

class TimerAddViewModel {
    
    private var name: String = kTimerDefaultName
    private var type: TimerType = .timeSlotTiming
    
    private var color: UIColor = .gray
    private var startTime: Time?
    private var endTime: Time?
    private var duration: Int?
    
    private var customTimer: CustomTimer?
    
    init(customTimer: CustomTimer?) {
        self.customTimer = customTimer
        self.color = customTimer?.color ?? .gray
        self.name = customTimer?.name ?? kTimerDefaultName
        
        if let sTime = customTimer?.startTime {
            startTime = Time(seconds: sTime)
        }
        if let eTime = customTimer?.endTime {
            endTime = Time(seconds: eTime)
        }
        
        if let id = customTimer?.type {
            self.type = TimerType.getType(id: id)
        }
    }
    
    @discardableResult
    func loadData() -> [BaseSectionModel] {
        var cellModels = [BaseCellModel]()
        var customModels = [BaseCellModel]()
        
        // 标题
        let inputCellModel = SettingOnlyInputCellModel(title: customTimer?.name, rowHeight: 80)
        inputCellModel.inputResult = { [weak self] content in
            self?.name = content ?? kTimerDefaultName
        }
        cellModels.append(inputCellModel)
        
        // 类型，减一是因为数字差一
        var index: Int = 0
        if customTimer == nil {
            index = Int(type.id - 1)
        } else {
            index = Int((customTimer?.type ?? 1) - 1)
        }
        let segmentCellModel = TimerTypeSegmentedCellModel(selectedSegmentIndex: index, rowHeight: 60)
        segmentCellModel.segmentedControlResult = { [weak self] content in
            let t = TimerType(rawValue: content ?? "") ?? .timeSlotTiming
            self?.type = t
            self?.customTimer?.type = t.id
            NotificationCenter.default.post(name: .refreshTimerAddController, object: nil, userInfo: nil)
        }
        cellModels.append(segmentCellModel)
        
        if type == .timeSlotTiming {
            if (customTimer?.startTime ?? 0) > 0 {
                startCellModel.detailTitle = customTimer?.startTime.et.formatTime("HH:mm") ?? ""
            }
            if (customTimer?.endTime ?? 0) > 0 {
                endCellModel.detailTitle = customTimer?.endTime.et.formatTime("HH:mm") ?? ""
            }
            cellModels.append(startCellModel)
            cellModels.append(endCellModel)
        } else if type == .countDown {
            if let duration = customTimer?.duration, duration > 0 {
                timerPickerCellModel.duration = Int(duration / 60)
            }
            timerPickerCellModel.pickerViewResult = { [weak self] minute in
                self?.duration = minute
            }
            cellModels.append(timerPickerCellModel)
        }
        
        let ringCellModel = SettingArrowCellModel(title: "铃声", tag: Tag.timerStartTime.rawValue)
        let cueCellModel = SettingArrowCellModel(title: "提示语", tag: Tag.timerStartTime.rawValue)
        if let color = customTimer?.color {
            colorCellModel.color = color
        }
        customModels.append(colorCellModel)
        customModels.append(ringCellModel)
        customModels.append(cueCellModel)
        
        var sections = [BaseSectionModel]()
        let section1 = BaseSectionModel(items: cellModels)
        let section2 = BaseSectionModel(items: customModels)
        sections.append(section1)
        sections.append(section2)
        
        return sections
    }
    
    func setTimerTime(hour: Int, minute: Int, timeType: TimeType) {
        let time = Time(hour: hour, minute: minute)
        let timeStr = String(format: "%.2d:%.2d", hour, minute)
        if timeType == .start {
            startTime = time
            startCellModel.detailTitle = timeStr
        } else if timeType == .end {
            endTime = time
            endCellModel.detailTitle = timeStr
        }
    }
    
    func setTimerColor(_ color: UIColor) {
        self.color = color
        colorCellModel.color = color
    }
    
    /// 保存
    func save() -> Bool {
        if !verifyData() { return false }
        
        var timer = XCCustomTimer()
        if let uuid = customTimer?.uuid {
            timer.uuid = uuid
        } else {
            timer.uuid = UUID().uuidString
        }
        
//        timer.uuid = "1500"
        timer.name = name
        timer.type = type
        timer.color = color
        //        timer.bell =
        //        timer.duration =
        
        switch type {
        case .timeSlotTiming: setStartAndEndTime(timer: &timer)
        case .timer: break
        case .countDown: setDuration(timer: &timer)
        }
        
        CustomTimerStore.save(timer: timer)
        
        return true
    }
    
    /// 倒计时，设置持续时间
    private func setDuration(timer: inout XCCustomTimer) {
        timer.duration = Double((duration ?? 0) * 60)
    }
    
    /// 时间段计时，设置开始结束时间
    private func setStartAndEndTime(timer: inout XCCustomTimer) {
        guard let startTime = startTime, let endTime = endTime else {
            return
        }
        
        var startTimestamp = kBaseTimestamp
        var endTimestamp = kBaseTimestamp

        /// 🌰例子：23:00 ~ 01:00
        /// 结束时间计算如下：
        /// 先算23:00 ~ 00:00的时间戳间隔
        /// 再加上00:00 ~ 01:00的时间戳间隔
        if startTime.hour > endTime.hour {
            startTimestamp = startTimestamp + Double(startTime.toSeconds())
            
            let hourNum = 24 - startTime.hour
            let seconds = (hourNum * 60 * 60) + (endTime.hour * 60 * 60) + startTime.minute * 60 + endTime.minute * 60
            endTimestamp = startTimestamp + Double(seconds)
        } else {
            startTimestamp = startTimestamp + Double(startTime.toSeconds())
            endTimestamp = endTimestamp + Double(endTime.toSeconds())
        }
        
        MyLog("startTimestamp:\(startTimestamp)")
        MyLog("endTimestamp:\(endTimestamp)")
        
        timer.startTime = startTimestamp
        timer.endTime = endTimestamp
    }
    
    private func verifyData() -> Bool {
        if type == .timeSlotTiming {
            guard let startTime = startTime else {
                SVProgressHUD.showError(withStatus: "请填写开始时间")
                return false
            }
            
            guard let endTime = endTime else {
                SVProgressHUD.showError(withStatus: "请填写结束时间")
                return false
            }

            if startTime == endTime {
                SVProgressHUD.showError(withStatus: "开始时间和结束时间不能一致")
                return false
            }
            
            if startTime.hour == endTime.hour {
                if startTime.minute > endTime.minute {
                    SVProgressHUD.showError(withStatus: "时间间隔不合理")
                    return false
                }
            }
        } else if type == .countDown {
            
        }
        
        return true
    }
    
    // MARK: - lazy
    
    private lazy var startCellModel: SettingArrowCellModel = {
        let model = SettingArrowCellModel(title: "开始时间", detailTitle: nil, tag: Tag.timerStartTime.rawValue)
        return model
    }()
    
    private lazy var endCellModel: SettingArrowCellModel = {
        let model = SettingArrowCellModel(title: "结束时间", detailTitle: nil, tag: Tag.timerEndTime.rawValue)
        return model
    }()
    
    private lazy var timerPickerCellModel: TimerPickerCellModel = {
        let model = TimerPickerCellModel(rowHeight: 120)
        return model
    }()
    
    private lazy var colorCellModel: SettingColorCellModel = {
        let model = SettingColorCellModel(title: "颜色", color: .gray, tag: Tag.setttingColor.rawValue)
        return model
    }()
}
